import React, { useEffect, useState, } from 'react'
import { Col, Form, Input, Button, Table, message, Select, DatePicker  } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import {
  fetchWholeStaff,
  reminding,
} from '@/services/distribution/whole'
import moment from 'moment'
import { getToken, exportsExcel } from '@/utils/utils'
import { connect } from 'dva'

const { RangePicker } = DatePicker
const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const columns = [
  {
    title: '序号',
    dataIndex: 'sort',
    key: 'sort',
    render(text, record, index){
      return <div>{index + 1}</div>
    }
  },
  {
    title: '编号',
    dataIndex: 'number',
    key: 'number',
  },
  {
    title: '门店名称',
    dataIndex: 'storeName',
    key: 'storeName',
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '总分销额',
    dataIndex: 'totalDistribution',
    key: 'totalDistribution',
  },
  {
    title: '总分销佣金',
    dataIndex: 'commissionVal',
    key: 'commissionVal',
    render(t){
      return <>{t || 0}</>
    }
  },
  {
    title: '已返佣金',
    dataIndex: 'cashBonusAmount',
    key: 'cashBonusAmount',
  },
  {
    title: '今日转发',
    dataIndex: 'todaysRelayAmount',
    key: 'todaysRelayAmount',
  },
  {
    title: '曝光',
    dataIndex: 'exposure',
    key: 'exposure',
  },
  {
    title: '开通时间',
    dataIndex: 'createTime',
    key: 'createTime',
    render(t){
      return <>{moment(t).format('YYYY-MM-DD')}</>
    }
  },
];

const Staff = props => {
  const { form, stores, merchants, dispatch } = props
  const { getFieldDecorator } = form
  const [data, setData] = useState([])
  const [total, setTotal] = useState(null)
  const [record, setRecord] = useState('')
  useEffect(() => {
    init()
    dispatch({
      type: 'distribute/fetchMerchants'
    })
  }, [])

  const init = async params => {
    const res = await fetchWholeStaff(params)
    setData(res.data)
    setTotal(res.total)
  }

  const oneKeyRemind = async params => {
    const res = await reminding(params)
    message.success(res.msg)
  }

  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      init({
        ...values,
        staffManage: {
          name: values.name,
          phone: values.phone,
        },
        startTime: values.time && moment(values.time[0]).format('YYYY-MM-DD hh:mm:ss'),
        endTime: values.time && moment(values.time[1]).format('YYYY-MM-DD hh:mm:ss'),
      })
    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
    init()
  }
  // 查询条件
  const getFields = () => {
    return(
      <>
        <Col span={8}>
          <Form.Item label={`姓名`}>
            {getFieldDecorator(`name`, {})
              (<Input />)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`手机号`}>
            {getFieldDecorator(`phone`, {})
              (<Input />)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`所属商户`}>
            {getFieldDecorator(`supplierId`, {})
              (<Select onChange={selectMerchant}>
                {
                  merchants && merchants.map(m => <Select.Option key={m.id} value={m.id}>{m.merchantName}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`门店`}>
            {getFieldDecorator(`storeId`, {})
              (<Select>
                {
                  stores && stores.map(m => <Select.Option key={m.id} value={m.id}>{m.name}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`开通时间`}>
            {getFieldDecorator(`time`, {})
              (<RangePicker
                showTime
                format={'YYYY/MM/DD HH:mm:ss'}
                placeholder=''
              />)}
          </Form.Item>
        </Col>
      </>
    )
  }

  const selectMerchant = (val) => {
    dispatch({
      type: 'distribute/fetchStores',
      payload: {
        supplierId: val,
        pageSize: 999,
      }
    })
  }

  // 按钮处理
  const handleBtn = type => {
    if (record.length == 0) return message.warn('请选择数据')
    switch (type) {
      case 96:
        return oneKeyRemind({
          staffId: record[0].id,
        })  
      case 97: // 导出excel
        return exportsExcel({
          columns,
          data,
          title: '员工分销',
        })
      default:
        break;
    }
  }
  const pagination = {
    total: parseInt(total),
    onChange(page) {
      init({
        pageNo: page,
      })
    }
  }
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setRecord(selectedRows)
    },
  };

  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table 
        columns={columns}
        dataSource={hasSearchBtn ? data : []}
        rowKey={record => record.id}
        pagination={pagination}
        rowSelection={rowSelection}
      />
    </PageHeaderWrapper>
    )
}

export default connect(({ distribute, }) => ({
  merchants: distribute.merchants,
  stores: distribute.stores,
}))(Form.create()(Staff))
